//
//  PageControlView.m
//
//  Created by Hunk on 11-12-22.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "PageControlView.h"

#define ELLIPSE_DIAMETER (8.0)
#define ELLIPSE_SPACE    (4.0)

@implementation PageControlView
@synthesize numberOfPages = _numberOfPages;
@synthesize currentPage   = _currentPage;
@synthesize delegate      = _delegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        _ellipseArray        = [[NSMutableArray alloc] init];
        _numberOfPages       = 0;
        _currentPage         = 0;
        _ellipseColor        = [UIColor whiteColor];
        _currentEllipseColor = [UIColor redColor];
    }
    return self;
}

- (void)setCurrentPage:(NSInteger)currentPage
{
    _currentPage = currentPage;
    
    [self setNeedsDisplay];
}

- (void)setNumberOfPages:(NSInteger)numberOfPages
{
    _numberOfPages = numberOfPages;
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetAllowsAntialiasing(context, YES);
    
    CGFloat origin_X = (self.bounds.size.width - ELLIPSE_DIAMETER * _numberOfPages - ELLIPSE_SPACE * (_numberOfPages - 1)) / 2.0;
    CGFloat origin_Y = (self.bounds.size.height - ELLIPSE_DIAMETER) / 2.0;
    
    for(int i = 0; i < _numberOfPages; i++)
    {
        if(i == _currentPage)
        {
            CGContextSetFillColorWithColor(context, _currentEllipseColor.CGColor);
        }
        else
        {
            CGContextSetFillColorWithColor(context, _ellipseColor.CGColor);
        }
        
        // 左右居中, 上下居中
        CGRect ellipseRect = CGRectMake(origin_X + i * (ELLIPSE_DIAMETER + ELLIPSE_SPACE), origin_Y, ELLIPSE_DIAMETER, ELLIPSE_DIAMETER);
        
        if([_ellipseArray count] < _numberOfPages)
        {
            [_ellipseArray addObject:NSStringFromCGRect(ellipseRect)];
        }
        
        CGContextFillEllipseInRect(context, ellipseRect);
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(nil == _delegate)
    {
        return;
    }
    
    UITouch* touch = [touches anyObject];
    
    CGPoint touchPoint = [touch locationInView:self];
    
    for(int i = 0; i < [_ellipseArray count]; i++)
    {
        CGRect ellipseRect = CGRectFromString([_ellipseArray objectAtIndex:i]);
        
        if(CGRectContainsPoint(ellipseRect, touchPoint))
        {   
            if([_delegate respondsToSelector:@selector(pageControlView:didSelectPageAtIndex:)])
            {
                [_delegate pageControlView:self didSelectPageAtIndex:i];
                
                return;
            }
        }
    }
}

- (void)dealloc
{
    _ellipseArray = nil;
    [_ellipseArray release];
}

@end
